<template>
  <div ref="dplayerContainer" class="dplayer"></div>
</template>

<script>
import DPlayer from 'dplayer';
import { defineExpose, ref } from 'vue';
import flvjs from 'flv.js';
import { printInfo } from '@/util/log';
import Hls from 'hls.js';

export default {
  name: 'VideoPlayer',
  props: {
    videoSrc: {
      type: String,
      required: true,
    },
    videoTitle: {
      type: String,
      default: 'Video Title',
    },
  },
  setup() {
    const player = ref(null);

    const play = () => {
      if (player.value) {
        player.value.play();
      }
    };

    const pauses = () => {
      if (player.value) {
        player.value.pause();
      }
    };

    defineExpose({ play, pauses });

    return {
      player,
    };
  },
  mounted() {
    this.initializePlayer(this.videoSrc);
  },
  methods: {
    initializePlayer(videoSrc) {
      const customType = {
      customHls: (video, player) => {
        const hls = new Hls();
        hls.loadSource(this.videoSrc); // 使用 props.videoSrc
        hls.attachMedia(video);
        hls.on(Hls.Events.MANIFEST_PARSED, () => {
          player.play();
        });
      },
      customFlv: (video, player) => {
        if (flvjs.isSupported()) {
          const flvPlayer = flvjs.createPlayer({
            type: 'flv',
            url: this.videoSrc, // 使用 props.videoSrc
          });
          flvPlayer.attachMediaElement(video);
          flvPlayer.load();
          flvPlayer.play();
          player.play()
        } else {
          printInfo({ title: "哎呀出错啦", text: 'FLV is not supported in this browser.', type: "error", plain: true });
        }
      },
    };

      this.player = new DPlayer({
        container: this.$refs.dplayerContainer,
        live: false,
        hotkey: true,
        screenshot: true,
        autoplay: false,
        mutex: true,
        preload: 'auto',
        video: {
          url: videoSrc,
          pic: import.meta.env.VITE_API_HOST + '/banner/20200717164221_WhUUt.jpeg', // 视频缩略图
          type: videoSrc.endsWith('.m3u8') ? 'customHls' : 'auto',
          customType: customType,
        },
        title: this.videoTitle,
      });
    },
  },
  watch: {
    videoSrc(newUrl) {
      if (this.player) {
        this.player.switchVideo({
          url: newUrl,
        });
        this.initializePlayer(newUrl); // 重新初始化播放器
      }
    },
  },
  beforeUnmount() {
    if (this.player) {
      this.player.destroy();
    }
  },
};
</script>

<style scoped>
.dplayer {
  width: 100%;
  border-radius: 10px 10px 0 0;
}

@media (min-width: 768px) {
  .dplayer {
    height: 500px; /* 中等屏幕高度 */
  }
}

@media (min-width: 1024px) {
  .dplayer {
    height: 500px; /* 大屏幕高度 */
  }
}

@media (min-width: 1200px) {
  .dplayer {
    height: 400.67px; /* 更大屏幕高度 */
  }
}
</style>
